import Message from "./Message";
import moment from "moment";
import axios from 'axios';
import CryptoJS from "crypto-js";
import UserSession from "@/UserSession";
import { notification, Icon, message } from "antd";
import { JSEncrypt } from 'jsencrypt';

function encrypt(encryptString) {
  const PUBLIC_KEY = "biaopin123456789";
  const key = CryptoJS.enc.Utf8.parse(PUBLIC_KEY);
  const srcs = CryptoJS.enc.Utf8.parse(encryptString);
  const encrypted = CryptoJS.AES.encrypt(srcs, key, {
    mode: CryptoJS.mode.ECB,
    padding: CryptoJS.pad.Pkcs7,
  });
  return encrypted.toString();
};

const key = "notificationKey"; // 设置消息通知框唯一的key

function checkStatus(status, msg) {
  if (status === 401) {
    notification.open({
      key,
      message: msg,
      icon: <Icon type='close-circle' style={{ color: "red" }} />,
    });
    window.g_app._store.dispatch({
      type: "login/logout",
    });
    localStorage.clear();
    return;
  }
  // environment should not be used
  if (status === 403) {
    router.push("/exception/403");
    return;
  }
  if (status <= 504 && status >= 500) {
    router.push("/exception/500");
    return;
  }
  if (status >= 404 && status < 422) {
    router.push("/exception/404");
  }
  if (status === 402) {
    return notification.open({
      key,
      message: msg,
      icon: <Icon type='close-circle' style={{ color: "red" }} />,
    });
  }

  return notification.open({
    key,
    message: msg,
    icon: <Icon type='close-circle' style={{ color: "red" }} />,
  });
}

//RSA加密
function rsaEncrypt(token, robotId) {
  const PUBLIC_KEY = "MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBALBGQ6yVSVjLNSompRSrkDReWYNdY4pPOoiabtCrDB+yKhMIIIHLJi5Z89cqvqjvkMvrXxXzl056IOQNM+Wdh60CAwEAAQ==";
  const currentTime = new Date().getTime();
  const encryptor = new JSEncrypt();
  encryptor.setPublicKey(PUBLIC_KEY)
  let data = token + '_' + currentTime
  let cptData = encryptor.encrypt(data)
  return encodeURIComponent(cptData)
}

const robotDataClass = {
  source: null,
  eventSource: null,
  createMessageID: function () {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    };
    s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = "-";
    return s.join("");
  },
  getHeaderData: function () {
    const currentTime = new Date().getTime();
    const headData = {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${UserSession.getToken()}`,
      lid: currentTime,
      sign: encrypt(JSON.stringify(currentTime)),
    };
    return headData;
  },

  /**
   * 【START】获取应用ID
   */
  getApplicationId: function (body, callback) {
    const headData = this.getHeaderData();
    axios.get("/cloud/application/base/getSysAppInfo", { params: body, headers: headData }).then(response => {
      if (response.data.code === 0) {
        if (callback) {
          callback(response);
        }
      } else {
        checkStatus(response.data.code, response.data.message);
      }
    });
  },

  initSSO: function (applicationId, param) {
    const headData = this.getHeaderData();
    return axios.post("/cloud/application/sso2", {
      param,
      applicationId
    }, {
      headers: headData
    });
  },

  /**
   * 【START】根据应用ID查询接入设置
   */
  getLinkByApplicationId: function (body, callback) {
    axios.post("/cloud/robotcustom/getApplicationInfo", body).then(response => {
      if (response.data.code === 0) {
        if (callback) {
          callback(response);
        }
      } else {
        checkStatus(response.data.code, response.data.message);
      }
    });
  },

  /**
   * 【START】获取websettingInfo
   */
  getWebSettingInfoByApplicationId: function (body, callback) {
    axios.get("/cloud/robotcustom/getWebSettingInfo", { params: body }).then(response => {
      if (response.data.code === 0) {
        if (callback) {
          callback(response);
        }
      } else {
        checkStatus(response.data.code, response.data.message);
      }
    });
  },

  /**
   * 【ING】机器人初始化接口
   */
  apiInitRobot: function (sessionId, params, robotId, callback) {
    //获取引擎初始化token
    robotDataClass.getInitToken(sessionId, robotId, (data) => {
      params.sign = data;
      axios.post("/engine-api/api/robot/session/init/" + sessionId, params).then(res => {
        console.log(res);
        console.log("机器人初始化" + res.data.success);
        if (res.data.success) {
          if (res.data.msg) {
            return notification.open({
              key,
              message: res.data.msg,
              icon: <Icon type='close-circle' style={{ color: "red" }} />,
            });
          };
          if (callback) {
            callback();
          }
        } else {
          notification.open({
            key,
            message: '初始化失败，请联系管理员',
            icon: <Icon type='close-circle' style={{ color: "red" }} />,
          });
        }
      });
    })

  },
  // 最新问答接口
  startStreaming(question, customerId, sessionId, bindId, chatId, callback) {
    let _this = this;

    //获取问答接口的token
    robotDataClass.getAnswerToken(sessionId, bindId, (resData) => {
      var data = {
        question: question.replace(/<[^>]+>/g, ""),
        channel: 'sys_web',
        userId: customerId,
        sessionId: sessionId,
        robotId: bindId,
        sign: resData
      };

      var params = 'question=' + encodeURIComponent(question.replace(/<[^>]+>/g, "")) + '&channel=sys_web' + '&userId=' + customerId + '&sessionId=' + sessionId + '&robotId=' + bindId + '&sign=' + resData;
      if (chatId) {
        params = 'question=' + encodeURIComponent(question.replace(/<[^>]+>/g, "")) + '&channel=sys_web' + '&userId=' + customerId + '&sessionId=' + sessionId + '&robotId=' + bindId + '&chatId=' + chatId + '&sign=' + resData;
      };
      _this.source = new EventSource(robotEngine + '/api/streamAnswer?' + params);

      _this.source.onopen = function (e) {
        console.log("建立连接。。。", e);
      };

      /**
       * 客户端收到服务器发来的数据
       * 另一种写法：source.onmessage = function (event) {}
       */
      _this.source.onmessage = function (e) {
        // console.log(e);
        if (e && e.data) {
          setTimeout(() => {
            _this.onMessage(e.data, callback);
          }, 150)
        }
      };

      /**
       * 如果发生通信错误（比如连接中断），就会触发error事件
       * 或者：
       * 另一种写法：source.onerror = function (event) {}
       */
      _this.source.onerror = function (e) {
        if (e.readyState === EventSource.CLOSED) {
          console.log("连接关闭");
        } else {
          console.log(e);
        };
        _this.source.close();
      };
    })

    // source.close()
  },
  // 接收消息
  onMessage: function (msg, callback) {
    // console.log(msg);
    let data = JSON.parse(msg);
    // console.log(data);
    if (data.type == "final" || data.type == 'error') {
      this.source.close();
    };
    if (callback) {
      callback(data)
    }
  },
  // 停止AI生成
  closeSource: function (callback) {
    if (this.source) {
      this.source.close();
      callback();
    };
  },
  // 关闭流式问答
  stopStreaming: function (id, callback) {
    axios.get("/engine-api/api/stopStreamAnswer", { params: { chatId: id } }).then(response => {
      if (response.data.code === 200 && response.data.data) {
        if (callback) {
          callback();
        }
      } else {
        checkStatus(response.data.code, response.data.message);
      }
    });
  },

  // 处理问题的数据
  onSetQuestion: function (question, sessionId, callback) {
    var time = new Date().getTime();
    var questionMessage = {
      messageId: "MessageId" + this.createMessageID(),
      sessionId,
      messageContent: question,
      messageDirection: 'C',
      messageType: 'T',
      recallTime: time,
      sendTime: time,
      messageStatus: 10,
    };
    var message = new Message(questionMessage);
    if (callback) {
      callback(message)
    };
  },
  // 处理知识点问答的数据
  onSetAnswer: function (data, sessionId, customerId, callback) {
    var createTime = data.createTime;
    if (createTime == undefined) {
      createTime = new Date().getTime();
    } else {
      createTime = moment(createTime, 'YYYY-MM-DD HH:mm:ss').valueOf();
    };
    for (var i = 0; i < data.answers.length; i++) {
      var answer = data.answers[i];
      answer.mainQuestion = data.question;
      var answerMessage = {
        chatId: data.chatId,
        messageId: "MessageId" + this.createMessageID(),
        sessionId,
        messageDirection: 'U',
        messageType: 'R',
        createTime,
        messageStatus: 10,
        customerId,
        messageContent: JSON.stringify(answer),
      };
      var message = new Message(answerMessage);
      if (callback) {
        callback(message)
      };
    }
  },
  // 处理流式问答的数据
  onSetAnswerInfo: function (data, sessionId, customerId, callback) {
    var createTime = data.createTime;
    if (createTime == undefined) {
      createTime = new Date().getTime();
    } else {
      createTime = moment(createTime, 'YYYY-MM-DD HH:mm:ss').valueOf();
    };
    var answer = data.answers[0];
    answer.mainQuestion = data.question;
    var answerMessage = {
      ...data,
      messageId: "MessageId" + this.createMessageID(),
      sessionId,
      messageDirection: 'U',
      messageType: 'T',
      createTime,
      messageStatus: 10,
      customerId,
      messageContent: JSON.stringify(answer),
    };
    var message = new Message(answerMessage);
    if (callback) {
      callback(message)
    };
  },

  // 问答接口
  getRobotAnswer: function (question, customerId, sessionId, bindId, touchWay) {
    var questionParams = {
      question: question.replace(/<[^>]+>/g, ""),
      channel: 'web',
      userId: customerId,
      sessionId: sessionId,
      robotId: bindId,
      touchWay: touchWay
    };
    axios.post('/engine-api/api/answer/' + sessionId, questionParams, function (res) {
      console.log('这里是答案呀====', res);
      const data = res.data;
      var createTime = data.createTime;
      if (createTime == undefined) {
        createTime = new Date().getTime();
      } else {
        createTime = moment(createTime, 'YYYY-MM-DD HH:mm:ss').valueOf();
      };
      // commonDataClass.currentAnswerChatId = data.chatId;
      for (var i = 0; i < data.answers.length; i++) {
        var answer = data.answers[i];
        answer.mainQuestion = data.question;
        var answerMessage = {
          messageId: "MessageId" + this.createMessageID(),
          sessionId,
          messageDirection: 'U',
          messageType: 'R',
          createTime,
          messageStatus: 10,
          customerId,
          messageContent: JSON.stringify(answer),
        };
        var message = new Message(answerMessage);
        if (callback) {
          callback(message)
        };
      }
    })
  },
  /**
   * 获取时间最早的一条消息
   */
  getForemostMessage: function (messages) {
    if (messages === null || messages.length === 0) {
      return null;
    };
    var e = messages.find(d => d.messageId != null);
    return e == undefined ? null : e;
  },
  /**
   * 【ING】转JSON
   */
  isJSON: function (str) {
    if (typeof str == "string") {
      try {
        var obj = JSON.parse(str);
        if (typeof obj == "object" && obj) {
          return true;
        } else {
          return false;
        }
      } catch (e) {
        return false;
      }
    };
    return false;
  },
  //加载历史记录
  getRobotHistoryMessage: function (row, sessionId, customerId, bindId, messages, callback) {
    var _this = this;
    var foremostMessage = this.getForemostMessage(messages);
    var params = { channel: 'web', userId: customerId, robotId: bindId, n: row ? row : 5, };
    if (foremostMessage != null) {
      params.createTime = moment(foremostMessage.sendTime * 1).format('YYYY-MM-DD HH:mm:ss');
    };
    axios.get('/cloud/custom/chat/latest', params, function (res) {
      if (res.success) {
        var list = res.data;
        this.hisyorySessionData(list, sessionId, customerId, callback);
      } else {
        console.log("加载历史聊天消息失败");
      };
      if (callback) {
        callback(res)
      }
    });
  },

  // 回到底部
  scrollToBottom: function () {
    var container = document.querySelector(".Message");
    if (container != undefined && container != null) {
      container.scrollTop = container.scrollHeight;
    }
  },

  // 回到顶部
  scrollToTop: function () {
    var container = document.querySelector(".Message");
    if (container != undefined && container != null) {
      container.scrollTop = container.clientTop;
    }
  },

  // 历史会话数据处理
  hisyorySessionData: function (list, sessionId, customerId, callback) {
    if (list.length > 0) {
      for (var i = (list.length - 1); i >= 0; i--) {
        const answer = list[i];
        answer.choices = [];
        answer.suggestions = [];
        answer.mainQuestion = answer.question;
        /* 处理json类型答案-需要再处理完answer后重新生成新的answerMessage */
        if (answer.answer && this.isJSON(answer.answer)) {
          console.log('这里是接送类型的答案---');
          const jsonContent = JSON.parse(answer.answer);
          answer.answer = jsonContent.data.guide ? jsonContent.data.guide : '';
        };

        let time = new Date(answer.time);

        // 问题
        if (list[i].question != 'qizhi_welcome' && list[i].question != '欢迎语') {
          var questionMessage = {
            messageId: "MessageId" + this.createMessageID(),
            sessionId,
            messageContent: list[i].question,
            messageDirection: 'C',
            messageType: 'T',
            recallTime: time,
            sendTime: time,
            messageStatus: 10,
          };
          var question = new Message(questionMessage);
          if (callback) {
            callback(question)
          };
        };

        // console.log(JSON.stringify(answer).match(/\!\[.*\]\(.+\)/));
        // console.log(JSON.stringify(answer).match(/<\?<=\!\[.*\]\(\)\(.+\)\(\?=\)\)/));
        // var IMAGE_PATTERN = /(?<=\!\[.*\]\()(.+)(?=\))/;
        // var result = IMAGE_PATTERN.exec(JSON.stringify(answer));
        // console.log(result);

        let reg = /\]\((.*?)\)/g;
        let dd = JSON.stringify(answer).match(reg);
        // console.log(JSON.stringify(answer));
        // console.log(dd);
        let answerText = JSON.stringify(answer);

        let regs = /\!\[.*?\]\((.*?)\)/g;
        let dds = JSON.stringify(answer).match(regs);
        console.log(dd);
        console.log(dds);
        if (dd && dd.length > 0) {
          dd.map((item, j) => {
            // let temp = item.replace(/(.*)\)/,'');
            let temp = item.replace(/(.*)\)/, '$1');
            temp = temp.replace('](', '');
            console.log(temp)
            answerText = answerText.replace(dds[j], `<img src='${temp}' />`);
          })
        }
        // console.log('111===========>>>>>>>>>>>>>', JSON.stringify(answer))
        // console.log('222===========>>>>>>>>>>>>>', answerText)


        // 答案
        var answerMessage = {
          ...answer,
          messageId: "MessageId" + this.createMessageID(),
          sessionId,
          messageDirection: 'U',
          messageType: 'R',
          readTime: time,
          messageStatus: 10,
          customerId,
          messageContent: answerText,
          recallTime: time,
          sendTime: time,
          chatId: answer.id,
        };
        /* json类型答案-message添加json类型 */
        if (answer.answer && this.isJSON(answer.answer)) {
          answerMessage.answerType = "json";
        };
        var message = new Message(answerMessage);
        if (callback) {
          callback(message)
        };
      }
    }
  },

  /**
   * 【ING】机器人回答是否解决
   */
  apiEvaluateRobotAnswer: function (solveStatus, robotId, item, callback) {
    if (item.messageType == "R" || item.messageType == "T") {
      try {
        var chatId = typeof item.chatId != 'undefined' ? item.chatId : JSON.parse(item.messageContent).chatId;
        axios.get("/cloud/custom/evaluation", {
          params: {
            chatId: chatId,
            channel: 'SYS_WEB',
            robotId,
            isResolved: solveStatus == "2" ? true : false
          }
        }).then(response => {
          if (response.data.code === 0) {
            if (callback) {
              callback(solveStatus)
            };
          } else {
            checkStatus(response.data.code, response.data.message);
          }
        });
      } catch (e) { }
    }
  },

  /**
   *  获取答案数据详情
   */
  getAnswerDataDetail: function (body, callback) {
    // const headData = this.getHeaderData();
    axios.get("/cloud/robotcustom/getAnswerSource", { params: body, /** headers: headData */ }).then(response => {
      if (response.data.code === 0) {
        if (callback) {
          callback(response);
        }
      } else {
        checkStatus(response.data.code, response.data.message);
      }
    });
  },
  /**
   * 获取init初始化接口的token
   */
  getInitToken: function (sessionId, robotId, callback) {
    axios.get("/engine-api/api/init/token?sessionId=" + sessionId + '&robotId=' + robotId, { sessionId, robotId }).then(res => {
      if (res.data.data) {
        callback(rsaEncrypt(res.data.data, robotId))
      } else {
        notification.open({
          key,
          message: '获取token失败',
          icon: <Icon type='close-circle' style={{ color: "red" }} />,
        });
      }
    });
  },

  /**
   * 获取问答接口的token
   */
  getAnswerToken: function (sessionId, robotId, callback) {
    axios.get("/engine-api/api/answer/token?sessionId=" + sessionId + '&robotId=' + robotId, { sessionId, robotId }).then(res => {
      if (res.data.data) {
        callback(rsaEncrypt(res.data.data, robotId))
      } else {
        notification.open({
          key,
          message: '获取token失败',
          icon: <Icon type='close-circle' style={{ color: "red" }} />,
        });
      }
    });
  }
}

export default robotDataClass
